import 'package:cloud_medicine/components/author_show.dart';
import 'package:cloud_medicine/components/comment_show.dart';
import 'package:cloud_medicine/components/favorite_icon.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/post_api.dart';
import 'package:cloud_medicine/main.dart';
import 'package:cloud_medicine/model/post_detail.dart';
import 'package:cloud_medicine/pages/edit_post.dart';
import 'package:cloud_medicine/pages/image_show.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class PostDetail extends StatefulWidget {
  final int postID; // 帖子ID

  PostDetail({Key key, @required this.postID}) : super(key: key);

  @override
  _PostDetailState createState() => _PostDetailState();
}

class _PostDetailState extends State<PostDetail> {
  bool _loading = false;
  PostDetailInfo _postDetail;

  @override
  void initState() {
    super.initState();
    _init();
  }

  // 初始化，向后端请求数据
  Future<Null> _init() async {
    setState(() {
      _loading = true;
    });
    dynamic res = await getPost_api('$backIP/post/getPostDetail', {
      'id': widget.postID,
    });
    if (mounted) {
      setState(() {
        if (res['code'] == 0) {
          _postDetail = PostDetailInfo.init(res['data']);
        } else {
          errorToast(res['message']);
        }
        _loading = false;
      });
    }
  }

  // 判断loading并且在loading为false时渲染主要视图
  Widget _childLayout() {
    if (_loading) {
      return Center(
        child: Container(
          child: CircularProgressIndicator(),
        ),
      );
    } else {
      return ListView(
        children: <Widget>[
          Container(
            color: Colors.white,
            padding: EdgeInsets.all(8),
            child: ListView(
              shrinkWrap: true, // 为true可以解决子控件必须设置高度的问题
              physics: NeverScrollableScrollPhysics(), // 禁用滑动事件
              children: <Widget>[
                AuthorShow(
                    userID: _postDetail.authorBasicInfo.id,
                    avatar: _postDetail.authorBasicInfo.avatar,
                    realname: _postDetail.authorBasicInfo.realname,
                    createTime: _postDetail.createTime,
                    widget: FavoriteIcon(
                      isLike: _postDetail.isLike,
                      like_num: _postDetail.like_num,
                      id: widget.postID,
                      isPost: true,
                    )),
                SizedBox(height: 10),
                SelectableText(_postDetail.content),
                SizedBox(height: 10),
                GridView.count(
                  physics: new NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  crossAxisSpacing: 10.0,
                  mainAxisSpacing: 10.0,
                  crossAxisCount: 3,
                  // 一行显示个数
                  childAspectRatio: 1.0,
                  children: getWidgetList(),
                ),
                SizedBox(height: 10),
              ],
            ),
          ),
          CommentShow(
            postID: widget.postID,
          )
        ],
      );
    }
  }

  // 生成gridView的网格视图图片
  List<Widget> getWidgetList() {
    return _postDetail.files.map((file) => getItemContainer(file)).toList();
  }

  // 生成每一张图片的样式
  Widget getItemContainer(String file) {
    return GestureDetector(
      child: Container(
        child: FadeInImage.assetNetwork(
          placeholder: 'images/loading.gif', // 占位图
          image: file,
        ),
        color: Colors.grey[100],
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => ImageShow(
                  url: file,
                )));
      },
    );
  }

  // 菜单栏子项
  SelectView(IconData icon, String text, String id) {
    return new PopupMenuItem<String>(
        value: id,
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            new Icon(icon, color: Colors.blue),
            new Text(text),
          ],
        ));
  }

  Future<void> _deletePost() async {
    // TODO: 将要删除的帖子ID传给后端|
    print(widget.postID);
    dynamic res = await deletePost_api('$backIP/post', {
      'id': widget.postID,
    });
    // TODO: 完善
    res['code'] == 0
        ? successToast(res['message'])
        : errorToast(res['message']);
    Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(
          builder: (BuildContext context) => MyHomePage(initIndex: 1)),
      ModalRoute.withName('/home'),
    );
  }

  // 修改或删除操作
  _operation(VoidCallback callback) {
    if (_postDetail.isMy) {
      callback();
    } else {
      Fluttertoast.showToast(
        msg: '对不起，你没有此权限',
        backgroundColor: Colors.black,
        textColor: Colors.white,
      );
    }
  }

  // 进入编辑帖子页面
  _entryEditPage() {
    Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
      return new EditPost(postID: widget.postID);
    })).then((value) {
      _init();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title: Text('帖子详情'),
        actions: <Widget>[
          new PopupMenuButton<String>(
            itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
              SelectView(Icons.edit, '修改', 'A'),
              SelectView(Icons.delete, '删除', 'B'),
            ],
            onSelected: (String action) {
              // 点击选项的时候
              switch (action) {
                case 'A':
                  _operation(_entryEditPage);
                  break;
                case 'B':
                  _operation(openAlertDialog(context, _deletePost, '确认删除该帖子？'));
                  break;
              }
            },
          ),
        ],
      ),
      body: _childLayout(),
    );
  }
}
